package de.traveltainment.concept.envers.api;

import de.traveltainment.concept.envers.audit.lifecycle.Lifecycle;
import de.traveltainment.concept.envers.audit.lifecycle.Stage;
import de.traveltainment.concept.envers.entities.Vito;
import de.traveltainment.concept.envers.repository.LifecycleRepositoy;
import de.traveltainment.concept.envers.repository.UploadRepository;
import org.hibernate.envers.AuditReader;
import org.hibernate.envers.AuditReaderFactory;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import java.util.List;

/**
 * Created by borlis on 16.06.2014.
 */
@RequestScoped
public class UploadManager {

    @Inject
    private UploadRepository uploadRepository;

    @Inject
    private LifecycleRepositoy lifecycleRepositoy;

    @Inject
    private EntityManager em;

    public void uploadConfiguration(Vito vito) {
        AuditReader reader = AuditReaderFactory.get(em);
        List<Number> list = reader.getRevisions(Vito.class, vito.getId());
        Lifecycle lifecycle = new Lifecycle();
        lifecycle.setIsActive(1);
        lifecycle.setVitoId(vito.getId());
        lifecycle.setRevId((Integer) list.get(list.size() - 1));
        lifecycle.setStage(Stage.waiting_for_upload);
        try {
            lifecycleRepositoy.create(lifecycle);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //Todo do real upload
    }

    public void uploadedSuccessfully(Vito vito) {
        Lifecycle waitingForUpload = lifecycleRepositoy.findWithStage(vito.getId(), Stage.waiting_for_upload);
        Lifecycle live = lifecycleRepositoy.findWithStage(vito.getId(), Stage.live);
        Lifecycle lastLive = lifecycleRepositoy.findWithStage(vito.getId(), Stage.last_live);
        lastLive.setIsActive(0);
        lifecycleRepositoy.update(lastLive);
        live.setStage(Stage.last_live);
        lifecycleRepositoy.update(live);
        waitingForUpload.setStage(Stage.live);
        lifecycleRepositoy.update(waitingForUpload);
    }
}
